package com.ysd.lis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysExtenFields;
import com.ysd.lis.entity.SysExtenFieldsValue;
import com.ysd.lis.mapper.sys.SysExtenFieldsMapper;
import com.ysd.lis.mapper.sys.SysExtenFieldsValueMapper;
import com.ysd.lis.request.ExtenFieldsValueDataResponseDto;
import com.ysd.lis.request.ExtenFieldsValuePageRequestDto;
import com.ysd.lis.request.ExtenFieldsValueResponseDto;
import com.ysd.lis.service.SysExtenFieldsValueService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 扩展字段值 服务实现类
 * </p>
 *
 * @author Cfz
 * @since 2023-12-22
 */
@Service
@Component
@Slf4j
public class SysExtenFieldsValueServiceImpl extends ServiceImpl<SysExtenFieldsValueMapper, SysExtenFieldsValue> implements SysExtenFieldsValueService {

    @Autowired
    SysExtenFieldsValueMapper sysExtenFieldsValueMapper;

    @Autowired
    SysExtenFieldsMapper sysExtenFieldsMapper;

    @Override
    public Result addExtenFieldsValue(SysExtenFieldsValue ExtenFieldsValue) {
        return null;
    }

    @Override
    public Result editExtenFieldsValue(SysExtenFieldsValue ExtenFieldsValue) {
        return null;
    }

    @Override
    public Result deleteExtenFieldsValue(SysExtenFieldsValue ExtenFieldsValue) {
        return null;
    }

    @Override
    public Result findExtenFieldsValueList(ExtenFieldsValuePageRequestDto pageParam) {
        ExtenFieldsValueResponseDto res = new ExtenFieldsValueResponseDto();

        List<String> listColumns = new ArrayList<>();
        //获取相应的表单数据
        LambdaQueryWrapper<SysExtenFields> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysExtenFields::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysExtenFields::getModuleId, pageParam.getModuleId());
        lambdaQueryWrapper.eq(SysExtenFields::getMenuId, pageParam.getMenuId());
        lambdaQueryWrapper.eq(SysExtenFields::getGroupCode, pageParam.getTabKey());
        List<SysExtenFields> sysExtenFields = sysExtenFieldsMapper.selectList(lambdaQueryWrapper);

        for (SysExtenFields item : sysExtenFields) {
            listColumns.add(item.getField());
        }
        res.setColumns(listColumns);

        //获取相关的表单对应值数据
        MPJLambdaWrapper<SysExtenFieldsValue> lambdaQueryWrapper1 = new MPJLambdaWrapper<>();
        lambdaQueryWrapper1.eq(SysExtenFieldsValue::getDelFlag, 0);
        lambdaQueryWrapper1.eq(SysExtenFieldsValue::getBusRowId, pageParam.getBusRowId());
        lambdaQueryWrapper1.in(SysExtenFieldsValue::getFieldId, sysExtenFields.stream().map(SysExtenFields::getId).collect(Collectors.toList()));
        lambdaQueryWrapper1.selectAll(SysExtenFieldsValue.class).selectAs("t1", SysExtenFields::getField, SysExtenFieldsValue::getFieldCode).selectAs("t1", SysExtenFields::getTitle, SysExtenFieldsValue::getFieldName).selectAs("t1", SysExtenFields::getCompType, SysExtenFieldsValue::getCompType).selectAs("t1", SysExtenFields::getFieldSource, SysExtenFieldsValue::getFieldSource).leftJoin(SysExtenFields.class, "t1", SysExtenFields::getId, SysExtenFieldsValue::getFieldId);
        List<SysExtenFieldsValue> sysExtenFieldsValues = sysExtenFieldsValueMapper.selectList(lambdaQueryWrapper1);

        List<ExtenFieldsValueDataResponseDto> listData = new ArrayList<>();

        for (SysExtenFieldsValue item : sysExtenFieldsValues) {
            ExtenFieldsValueDataResponseDto itm = new ExtenFieldsValueDataResponseDto();
            itm.setId(item.getId());
            itm.setFieldId(item.getFieldId());
            itm.setFieldCode(item.getFieldCode());
            itm.setFieldName(item.getFieldName());
            itm.setCompType(item.getCompType());
            itm.setFieldSource(item.getFieldSource());
            itm.setBusRowId(item.getBusRowId());
            itm.setValue(item.getValue());
            itm.setOrgId(item.getOrgId());
            itm.setDataType(item.getDataType());
            listData.add(itm);
        }

        //把有定义，数值表没有的也要加到数组中
        List<SysExtenFields> notHasValues = sysExtenFields.stream().filter(pp -> !sysExtenFieldsValues.stream().map(SysExtenFieldsValue::getFieldCode).collect(Collectors.toList()).contains(pp.getField())).collect(Collectors.toList());
        for (SysExtenFields item : notHasValues) {
            ExtenFieldsValueDataResponseDto itm = new ExtenFieldsValueDataResponseDto();
            itm.setId("");
            itm.setFieldId(item.getId());
            itm.setFieldCode(item.getField());
            itm.setFieldName(item.getTitle());
            itm.setCompType(item.getCompType());
            itm.setFieldSource(item.getFieldSource());
            itm.setBusRowId(pageParam.getBusRowId());
            itm.setValue(null);
            itm.setOrgId(item.getOrgId());
            /**
             * 数据类型 Strng,Integer,Date,Array<String>,Array<Integer>
             * */
            if (!item.getCompType().isEmpty() && item.getCompType().equals("switch")) {
                itm.setDataType("Integer");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("input")) {
                itm.setDataType("Strng");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("date")) {
                itm.setDataType("Strng");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("radiogroup")) {
                itm.setDataType("Strng");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("select")) {
                itm.setDataType("Strng");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("textarea")) {
                itm.setDataType("Strng");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("integer")) {
                itm.setDataType("Integer");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("checkbox")) {
                itm.setDataType("Integer");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("checkboxgroup")) {
                itm.setDataType("Array<String>");
            }
            if (!item.getCompType().isEmpty() && item.getCompType().equals("Array<Integer>")) {
                itm.setDataType("Array<Integer>");
            }
            listData.add(itm);
        }
        res.setData(listData);
        return Result.succ(1, "请求成功", res);
    }

    @Override
    public List<Map<String,String>> findDeeCodeExtenFieldsValueList(ExtenFieldsValuePageRequestDto pageParam) {

        List<String> listColumns = new ArrayList<>();
        //获取相应的表单数据
        LambdaQueryWrapper<SysExtenFields> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysExtenFields::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysExtenFields::getModuleId, pageParam.getModuleId());
        lambdaQueryWrapper.eq(SysExtenFields::getMenuId, pageParam.getMenuId());
        lambdaQueryWrapper.eq(SysExtenFields::getGroupCode, pageParam.getTabKey());
        List<SysExtenFields> sysExtenFields = sysExtenFieldsMapper.selectList(lambdaQueryWrapper);

        //获取相关的表单对应值数据
        pageParam.getBusRowIdMap().forEach((k, v) -> {
            listColumns.add(k);
        });
        MPJLambdaWrapper<SysExtenFieldsValue> lambdaQueryWrapper1 = new MPJLambdaWrapper<>();
        lambdaQueryWrapper1.eq(SysExtenFieldsValue::getDelFlag, 0);
        lambdaQueryWrapper1.in(SysExtenFieldsValue::getBusRowId, listColumns);
        lambdaQueryWrapper1.in(SysExtenFieldsValue::getFieldId, sysExtenFields.stream().map(SysExtenFields::getId).collect(Collectors.toList()));
        lambdaQueryWrapper1.selectAll(SysExtenFieldsValue.class).selectAs("t1", SysExtenFields::getField, SysExtenFieldsValue::getFieldCode).selectAs("t1", SysExtenFields::getTitle, SysExtenFieldsValue::getFieldName).selectAs("t1", SysExtenFields::getCompType, SysExtenFieldsValue::getCompType).selectAs("t1", SysExtenFields::getFieldSource, SysExtenFieldsValue::getFieldSource).leftJoin(SysExtenFields.class, "t1", SysExtenFields::getId, SysExtenFieldsValue::getFieldId);
        List<SysExtenFieldsValue> sysExtenFieldsValues = sysExtenFieldsValueMapper.selectList(lambdaQueryWrapper1);
        Map<String, List<SysExtenFieldsValue>> collect = sysExtenFieldsValues.stream().filter(item -> Objects.nonNull(item)).collect(Collectors.groupingBy(SysExtenFieldsValue::getBusRowId));
        //for循环map
        List<Map<String,String>>list=new ArrayList<>();
        for (Map.Entry<String, List<SysExtenFieldsValue>> dataList : collect.entrySet()) {
            List<SysExtenFieldsValue> deeCodeExtenFieldsValueList = dataList.getValue();
            String text= "";
            if (CollectionUtils.isNotEmpty(deeCodeExtenFieldsValueList)){
                for (SysExtenFieldsValue valueDataResponseDto : deeCodeExtenFieldsValueList) {
                    text+=valueDataResponseDto.getFieldName()+":"+(StringUtils.isNotBlank(valueDataResponseDto.getValue())?valueDataResponseDto.getValue():"")+" \n  ";
                }
            }
            Map<String,String> hashMap = new HashMap<>();
            hashMap.put("feeCode",pageParam.getBusRowIdMap().get(dataList.getKey()));
            hashMap.put("value",text);
            list.add(hashMap);
        }
        return list;
    }

    @Override
    @Transient
    public Result saveEditExtenFieldsValueList(ExtenFieldsValueResponseDto input) throws JsonProcessingException {
        List<String> Ids = input.getData().stream().map(ExtenFieldsValueDataResponseDto::getId).collect(Collectors.toList());

        MPJLambdaWrapper<SysExtenFieldsValue> lambdaQueryWrapper1 = new MPJLambdaWrapper<>();
        lambdaQueryWrapper1.eq(SysExtenFieldsValue::getDelFlag, 0);
        lambdaQueryWrapper1.in(SysExtenFieldsValue::getId, Ids);
        List<SysExtenFieldsValue> sysExtenFieldsValues = sysExtenFieldsValueMapper.selectList(lambdaQueryWrapper1);

        List<SysExtenFieldsValue> listAdd = new ArrayList<>();
        List<SysExtenFieldsValue> listUpdate = new ArrayList<>();
        for (ExtenFieldsValueDataResponseDto item : input.getData()) {
            if (ToolsUtils.isNotEmpty(item.getId())) {
                SysExtenFieldsValue entry = sysExtenFieldsValues.stream().filter(p -> p.getId().equals(item.getId())).findFirst().get();
                entry.setValue(item.getValue());
                listUpdate.add(entry);
            } else {
                SysExtenFieldsValue entry = new SysExtenFieldsValue();
                entry.setFieldId(item.getFieldId());
                entry.setFieldName(item.getFieldName());
                entry.setFieldSource(item.getFieldSource());
                entry.setFieldCode(item.getFieldCode());
                entry.setBusRowId(input.getBusRowId());
                entry.setDataType(item.getDataType());
                entry.setValue(item.getValue());
                listAdd.add(entry);
            }
        }

        boolean uFlag = this.updateBatchById(listUpdate);
        boolean aFlag = this.saveBatch(listAdd);
        if (ToolsUtils.isNotEmpty(listUpdate) && ToolsUtils.isNotEmpty(listAdd)) {
            return Result.succ(uFlag && aFlag ? 1 : 0, uFlag && aFlag ? "提交成功" : "提交失败", null);
        }
        if (ToolsUtils.isNotEmpty(listUpdate) && !ToolsUtils.isNotEmpty(listAdd)) {
            return Result.succ(uFlag ? 1 : 0, uFlag ? "提交成功" : "提交失败", null);
        }
        if (!ToolsUtils.isNotEmpty(listUpdate) && ToolsUtils.isNotEmpty(listAdd)) {
            return Result.succ(aFlag ? 1 : 0, aFlag ? "提交成功" : "提交失败", null);
        }
        return Result.fail("没有要保存的数据");
    }
}
